package com.cn.wanxi.dao.impl;

import com.cn.wanxi.dao.OnlineDao;
import com.cn.wanxi.model.OnlineModel;
import com.cn.wanxi.util.JDBC;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据持久层，和数据库打交道
 * 免不了 每一个都会去左增删查改的操作
 * 能不能将访问数据库的方式提取到一个工具类里面去？
 * JDBC链接数据
 * 手写JDBC的步骤？
 */
public class OnlineImpl implements OnlineDao {
    @Override
    public int add(OnlineModel onlineModel) {
        String sql = "insert into online" +
                "(name,email,phone,content) " +
                "values('"+onlineModel.getName()+"'," +
                "'"+onlineModel.getEmail()+"'," +
                "'"+onlineModel.getPhone()+"'," +
                "'"+onlineModel.getContent()+"')";
        return JDBC.update(sql);
    }

    @Override
    public int update(OnlineModel onlineModel) {
        String sql = "update online set " +
                "name='" + onlineModel.getName() + "' " +
                "where id=" + onlineModel.getId();
        return JDBC.update(sql);
    }

    @Override
    public int delete(OnlineModel onlineModel) {
        String sql = "delete from online where id=" + onlineModel;
        return JDBC.update(sql);
    }

    @Override
    public OnlineModel findById(OnlineModel onlineModel) {
        String sql = "select * from online where id=" + onlineModel.getId();
//        String sql = "select * from online where id=1";
        List<OnlineModel> list = getList(sql);
        return list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public List<OnlineModel> findAll(OnlineModel onlineModel) {
        String sql = "select * from online";
        return getList(sql);
    }

    private List<OnlineModel> getList(String sql) {
        ResultSet resultSet = JDBC.query(sql);
        List<OnlineModel> list = new ArrayList<>();
        try {
//            当resultSet里面有值，则进入while循环
            while (resultSet.next()) {
                OnlineModel model = new OnlineModel();
//                resultSet.getInt("id") 括号里面引号对应的是数据库查询出来的列名
                model.setId(resultSet.getInt("id"));
                model.setName(resultSet.getString("name"));
                list.add(model);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JDBC.close();
        }
        return list;
    }

    @Override
    public int getCount(OnlineModel onlineModel) {
        String sql = "select count(*) count from online";

        return JDBC.getCount(sql);
    }
}
